package sz.com.postoffice.jxyzwgcase.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.sun.istack.NotNull;
import io.swagger.annotations.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import sz.com.postoffice.jxyzwgcase.constants.Constants;
import sz.com.postoffice.jxyzwgcase.core.BaseResponseEntity;
import sz.com.postoffice.jxyzwgcase.core.TableDataInfo;
import sz.com.postoffice.jxyzwgcase.pojo.*;
import sz.com.postoffice.jxyzwgcase.service.EmolumentRuleService;
import sz.com.postoffice.jxyzwgcase.service.EmolumentTemplateService;
import sz.com.postoffice.jxyzwgcase.service.EmolumentResultService;
import sz.com.postoffice.jxyzwgcase.service.UserAdoService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "薪酬模板", tags = "{薪酬模板API}")
@RestController
@Slf4j
@RequestMapping(value = "/emolument")
public class EmolumentController {
    @Resource
    private EmolumentTemplateService templateService;

    @Resource
    private EmolumentRuleService ruleService;

    @Resource
    private EmolumentResultService resultService;


    @ApiOperation(value = "新增薪酬模板", notes = "新增薪酬模板")
    @RequestMapping(value = "/templates", method = RequestMethod.POST)
    public boolean insertTemplate(EmolumentTemplate template) {
        System.out.println("开始新增...");
        return templateService.insert(template);
    }

    @ApiOperation(value = "查询薪酬模板", notes = "查询薪酬模板")
    @RequestMapping(value = "/templates", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", dataType = "int", paramType = "path", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "int", paramType = "path", required = true)
    })
    public TableDataInfo findTemplateByInfo(EmolumentTemplate template) {
        System.out.println("开始查询...");
        return templateService.findByListEntity(template);
    }

    @ApiOperation(value = "查询模板规则详情", notes = "查询模板规则详情")
    @RequestMapping(value = "/rules/{templateCode}", method = RequestMethod.GET)
    public Map<String, Object> findById(@PathVariable("templateCode") @NotNull @ApiParam(name="模板code",value="path传入",required=true) String templateCode) {
        System.out.println("开始查询...");
        Map<String, Object> resultMap = new HashMap<>();
        EmolumentTemplate template = templateService.findByCode(templateCode);
        resultMap.put("template", template);
        List<EmolumentRule> ruleList = ruleService.findByTemplateCode(templateCode);
        resultMap.put("ruleList", ruleList);
        return resultMap;
    }

    @ApiOperation(value = "新增模板规则", notes = "新增模板规则")
    @RequestMapping(value = "/rules/{templateCode}", method = RequestMethod.POST)
    public boolean insertRule(@RequestBody List<EmolumentRule> ruleList,@PathVariable("templateCode") @NotNull @ApiParam(name="模板code",value="path传入",required=true) String templateCode) {
        if (ruleList == null) {
            return true;
        }
        System.out.println("开始新增...");
        for (EmolumentRule rule : ruleList) {
            if (rule.getType() == 0) {
                EmolumentTemplate emolumentTemplate = templateService.findByCode(templateCode);
                emolumentTemplate.setBasicSalary(rule.getFixedIncome());
                templateService.update(emolumentTemplate);
                continue;
            }
            ruleService.insert(rule);
        }
        return true;
    }

    @ApiOperation(value = "修改模板规则", notes = "修改模板规则")
    @RequestMapping(value = "/rules/{templateCode}", method = RequestMethod.PUT)
    public boolean updateRule(@RequestBody List<EmolumentRule> ruleList,@PathVariable("templateCode") @NotNull @ApiParam(name="模板code",value="path传入",required=true) String templateCode) {
        System.out.println("开始修改...");
        for (EmolumentRule rule : ruleList) {
            if (rule.getType() == 0) {
                EmolumentTemplate emolumentTemplate = templateService.findByCode(templateCode);
                emolumentTemplate.setBasicSalary(rule.getFixedIncome());
                templateService.update(emolumentTemplate);
                continue;
            }
            ruleService.update(rule);
        }
        return true;
    }

    @ApiOperation(value = "获取薪酬结果", notes = "获取薪酬结果")
    @RequestMapping(value = "/result", method = RequestMethod.GET)
    public Map<String, Object> getResult(EmolumentResult paramResult) {
        System.out.println("开始查询...");
        EmolumentResult emolumentResult = resultService.findByEntity(paramResult);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 200);
        resultMap.put("msg", "成功");
        if (emolumentResult == null) {
            return resultMap;
        }

        Income income = new Income();
        List<Detail> details = new ArrayList<>();
        income.setTotalValue(getDetailTotal(emolumentResult, details));
        income.setDetails(details);
        income.setStatistics(getStatisticList(emolumentResult));
        income.setRank(getRank(emolumentResult));

        resultMap.put("data", income);
        return resultMap;
    }

    @ApiOperation(value = "查询薪酬结果集", notes = "查询薪酬结果集")
    @RequestMapping(value = "/results", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", dataType = "int", paramType = "path", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "int", paramType = "path", required = true)
    })
    public TableDataInfo resultByMonth(EmolumentResult paramResult) {
        System.out.println("查询开始---");
        return resultService.findByListEntity(paramResult);
    }

    /**
     * 导出薪酬结果集
     *
     * @param paramResult
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "导出薪酬结果集", notes = "导出薪酬结果集")
    @RequestMapping(value = "/exportResults", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", dataType = "int", paramType = "path", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "int", paramType = "path", required = true)
    })
    public BaseResponseEntity exportResults(EmolumentResult paramResult, HttpServletResponse response) throws IOException {
        System.out.println("接收参数：" + paramResult);

        //一、从后台拿数据
        if (null == response) {
            return BaseResponseEntity.success(1, "导出失败,请联系管理员.", null);
        }

        //二、 数据转成excel
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-download");
        String fileName = ("薪酬统计.xlsx");
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

        XSSFWorkbook wb = resultService.exportResults(paramResult);
        OutputStream out = response.getOutputStream();
        wb.write(out);
        out.close();
        wb.close();
        return null;
    }


    private double getRank(EmolumentResult emolumentResult) {
        int moreThanCount = 0;
        double value = 0.0;
        List<EmolumentResult> resultList = resultService.getTotalByDeptAndPeriod(emolumentResult.getDeptCode(), emolumentResult.getPeriodId());
        for (int i = 0; i < resultList.size(); i++) {
            if (resultList.get(i).getEmpCode().equals(emolumentResult.getEmpCode())) {
                moreThanCount = resultList.size() - i - 1;
                value = resultList.get(i).getTotal();
            } else {
                if (moreThanCount > 0)
                {
                    double 差值 = resultList.get(i).getTotal() - value;
                    if (差值 < 0.00001 && 差值 > -0.000001)
                    {
                        moreThanCount--;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        return (double) moreThanCount / resultList.size() * 100;
    }

    private double getDetailTotal(EmolumentResult emolumentResult, List<Detail> detailList) {
        double total = 0.0;
        Detail detail1 = new Detail();
        detail1.setName("底薪");
        detail1.setValue(emolumentResult.getBasicSalary());
        detailList.add(detail1);
        total += detail1.getValue();
        Detail detail2 = new Detail();
        detail2.setName("投递提成");
        detail2.setValue(emolumentResult.getDeliverTotal() + emolumentResult.getDeliverCourtTotal());
        detailList.add(detail2);
        total += detail2.getValue();
        Detail detail3 = new Detail();
        detail3.setName("标快提成");
        detail3.setValue(emolumentResult.getStandardDeliveryTotal());
        detailList.add(detail3);
        total += detail3.getValue();
        Detail detail4 = new Detail();
        detail4.setName("快递包裹提成");
        detail4.setValue(emolumentResult.getExpressPackageTotal());
        detailList.add(detail4);
        total += detail4.getValue();
        Detail detail5 = new Detail();
        detail5.setName("国际提成");
        detail5.setValue(emolumentResult.getInternationalDeliveryTotal());
        detailList.add(detail5);
        total += detail5.getValue();
        return total;
    }

    private List<Statistic> getStatisticList(EmolumentResult emolumentResult) {
        List<Statistic> statistics = new ArrayList<>();

        Statistic statistic1 = new Statistic();
        statistic1.setName("总投递量");
        statistic1.setValue(emolumentResult.getDeliverNum() + emolumentResult.getDeliverCourtNum());
        statistics.add(statistic1);
        Statistic statistic2 = new Statistic();
        statistic2.setName("标快揽收量");
        statistic2.setValue(emolumentResult.getStandardDeliveryNum());
        statistics.add(statistic2);
        Statistic statistic3 = new Statistic();
        statistic3.setName("快递包裹揽收量");
        statistic3.setValue(emolumentResult.getExpressPackageNum());
        statistics.add(statistic3);
        Statistic statistic4 = new Statistic();
        statistic4.setName("国际快递揽收量");
        statistic4.setValue(emolumentResult.getInternationalDeliveryNum());
        statistics.add(statistic4);
        return statistics;
    }

    @Data
    public class Income
    {
        private double totalValue;

        private List<Detail> details;

        private List<Statistic> statistics;

        private double rank;
    }

    @Data
    public class Detail
    {
        private String name;

        private double value;
    }

    @Data
    public class Statistic
    {
        private String name;

        private Integer value;
    }
}
